<template>
    <div class="layout-editor-notify">

        <!-- 刺绣绣超出绣框 -->
        <div class="notify-oversize" v-if="oversizeDst && oversizeDst.length > 0"
             @click="setNotifyActive(oversizeDst[0])">
            <svg-icon name="notify2" />
            <span>Design exceeds embroidery frame. </span>
        </div>

        <!-- 刺绣绣版带重合 -->
        <div class="notify-overlap" v-else-if="overlapDst && overlapDst.length > 0"
             @click="setNotifyActive(overlapDst[0])">
            <svg-icon name="notify2" />
            <span>Overlapping designs found.</span>
        </div>

        <!-- 针数超出限制 -->
        <div class="notify-overlap" v-else-if="exceedStitches.length > 0" @click="setNotifyActive(exceedStitches[0])">
            <svg-icon name="notify2" />
            <span>Total stitch count exceeds the frame limit. Please remove some designs.</span>
        </div>


        <!-- 线色超出限制 -->
        <div class="notify-overlap" v-else-if="exceedColors.length > 0" @click="setNotifyActive(exceedColors[0])">
            <svg-icon name="notify2" />
            <span>Total color count exceeds the frame limit. Please remove some designs.</span>
        </div>


        <!-- dtg 清晰度 -->
        <div class="notify-clarity" v-else-if="clarity && clarity.length > 0" @click="setNotifyActive(clarity[0])">
            <svg-icon name="notify2" />
            <span>Low resolution artwork detected.<br />The low resolution of the uploaded file will affect the printing
                result. </span>
        </div>


    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import DesignUtils from '@/utils/DesignUtils.js';

export default {
    data () {
        return {
            timer: null,
        };
    },
    computed: {

        ...mapState("designer", { oversizeDst: "oversize_dst", overlapDst: "overlap_dst", exceedStitches: 'exceed_stitches', exceedColors: 'exceed_colors' }),
        ...mapGetters("designer", {
            models: "getModels",
            platens: "getPlatens",
            pieces: "getPieces",
            activePiece: "getActivePiece",
            activeLayer: "getActiveLayer",
            activeDst: "getActiveDst",
        }),
        clarity () {

            // 最小dei
            // 像素1:1时，dpi为300
            // 图片像素大于1:1像素条件下的75/300，即可
            let min_dpi = 75; // 最小dpi
            let now_dpi = 300; // 当前dpi
            let pieces = this.pieces;
            let unclear = []; // 不清晰列表

            pieces.map((piece) => {
                let scale = Math.max(
                    piece.real_width / piece.canvas_width,
                    piece.real_height / piece.canvas_height
                );
                (piece.layers || []).map((layer) => {
                    if (layer.type != "image") {
                        // 不是图片
                    } else {
                        let minW = (layer.w * scale * min_dpi) / now_dpi;
                        let minH = (layer.h * scale * min_dpi) / now_dpi;

                        let clearX = layer.cutW >= minW;
                        let clearY = layer.cutH >= minH;

                        !(clearX && clearY) && unclear.push({
                            piece: piece,
                            layer: layer,
                        });
                    }
                });
            });

            return unclear
        },
        // dstLayerWatcher () {
        //     if (this.activeLayer) {
        //         return [this.activeLayer.x, this.activeLayer.y]
        //     } else {
        //         return []
        //     }
        // },

        // dstLength () {
        //     return this.pieces.reduce((a, p) => a + p.layers.reduce((b, c) => p.type == 2 ? b + c.dists.length : b, 0), 0)
        // },
    },

    watch: {
        // 绣框位置变化
        // dstLayerWatcher () {
        //     this.timer && clearTimeout(this.timer)
        //     this.timer = setTimeout(() => {
        //         this.getEmbDstOverlap()
        //         this.timer = 0;
        //     }, 500);
        // },
        // dstLength () {
        //     this.getEmbPlatenExcess()
        //     this.getEmbPlatenColors()
        // },
        // activeDst: {
        //     deep: true,
        //     immediate: true,
        //     handler () {
        //         this.timer && clearTimeout(this.timer)
        //         this.timer = setTimeout(() => {
        //             this.getEmbDstOversize();
        //             this.getEmbDstOverlap()
        //             this.timer = 0;
        //         }, 100);
        //     }
        // }
    },
    methods: {
        // 获取绣框的冲突
        getEmbPlatenError () {
            const result = []
            this.pieces.map(piece => {
                if (piece.type == 2 && piece.layers.length > 1) {
                    const group = []
                    // 两两分组
                    piece.layers.map((first, index) => piece.layers.slice(index + 1).map(second => group.push([first, second])))

                    // 有重叠的组
                    const overlap = group.filter(list => {

                        const first = list[0];
                        const second = list[1];

                        if (!first || !second) {
                            return false;
                        } else {
                            const dx = Math.abs(first.x + 0.5 * first.w - second.x - 0.5 * second.w) - 0.5 * (second.w + first.w)
                            const dy = Math.abs(first.y + 0.5 * first.h - second.y - 0.5 * second.h) - 0.5 * (second.h + first.h)
                            return dx < 0 && dy < 0
                        }
                    })

                    if (overlap.length > 0) {
                        const map = new Map()
                        overlap.map(list => list.map(layer => map.set(layer, true)))
                        result.push({
                            piece: piece,
                            layers: Array.from(map.keys())
                        })
                    }
                }
            })
            this.$store.commit('designer/SET_OVERLAP_LAYERS', result)

        },

        // 获取超出的版带
        getEmbDstOversize () {
            const result = []



            this.pieces.map(piece => {
                if (piece.type == 2) {

                    piece.layers.map(layer => {
                        // 只有版带数量超过1时才判断
                        // const pixel =
                        layer.dists.map(dst => {

                            // 真实宽高
                            const real = DesignUtils.rectRealSize(dst.w, dst.h, dst.rotate)
                            // 移动限制
                            const range = {
                                minX: 0.5 * real.width - 0.5 * dst.w,
                                maxX: layer.w - 0.5 * real.width - 0.5 * dst.w,
                                minY: 0.5 * real.height - 0.5 * dst.h,
                                maxY: layer.h - 0.5 * real.height - 0.5 * dst.h
                            }

                            const dst_x = Math.round(dst.x * 10000)
                            const dst_y = Math.round(dst.y * 10000)
                            const in_x = dst_x >= Math.round(range.minX * 10000 - 1) && dst_x <= Math.round(range.maxX * 10000 + 1)
                            const in_y = dst_y >= Math.round(range.minY * 10000 - 1) && dst_y <= Math.round(range.maxY * 10000 + 1)
                            if (in_x && in_y) {
                                // 正常
                            } else {
                                result.push({
                                    piece: piece,
                                    layer: layer,
                                    dst: dst,
                                })
                            }

                        })

                    })
                }
            })


            this.$store.commit('designer/SET_OVERSIZE_DST', result)

        },

        // 跨绣框获取重叠的版带
        getEmbDstOverlap () {
            const result = []

            this.pieces.map(piece => {
                if (piece.type == 2) {

                    // 重叠的
                    const overlap = {
                        format: [],
                        active: [],
                        pixel: [],
                        size: Math.floor(piece.canvas_width - 1) * Math.floor(piece.canvas_height - 1),
                    }

                    piece.layers.map(layer => {
                        // 只有版带数量超过1时才判断
                        layer.dists.map(dst => {

                            const cav = document.createElement('canvas');
                            const ctx = cav.getContext("2d");

                            const center_x = layer.x + dst.x + 0.5 * dst.w;
                            const center_y = layer.y + dst.y + 0.5 * dst.h;

                            cav.width = piece.canvas_width;
                            cav.height = piece.canvas_height;
                            ctx.fillStyle = '#f00';

                            // 简单处理
                            ctx.translate(center_x, center_y);
                            ctx.rotate(dst.rotate * Math.PI / 180);
                            ctx.fillRect(-0.5 * dst.w, -0.5 * dst.h, dst.w, dst.h);
                            ctx.translate(-center_x, -center_y);

                            overlap.format.push({
                                piece: piece,
                                layer: layer,
                                dst: dst,
                            })

                            overlap.pixel.push(ctx.getImageData(0, 0, cav.width, cav.height).data || [])
                        })
                    })

                    while (--overlap.size >= 0) {
                        const alpha = overlap.pixel.map(pix => pix[overlap.size * 4 + 3])
                        const len = alpha.filter(i => i > 0).length
                        // 有重复的
                        if (len > 1) {
                            alpha.map((k, i) => k > 0 && overlap.active.indexOf(i) < 0 && overlap.active.push(i))
                            if (overlap.active.length >= overlap.format.length) {
                                break
                            }
                        }
                    }

                    if (overlap.active.length > 1) {
                        // 版带有重叠
                        result.push(...overlap.active.map(idx => overlap.format[idx]))
                    }
                }
            })
            this.$store.commit('designer/SET_OVERLAP_DST', result)

        },

        // 刺绣超出针数限制
        getEmbPlatenExcess () {
            const result = [];
            const platens = this.platens || [];
            this.pieces.map((piece) => {
                piece.layers.map((layer) => {
                    if (piece.type == 2) {
                        const active = platens.find((i) => i.code == layer.platens_id);
                        const max = active ? active.max_stitches : 0;
                        layer.stitches_count > max && result.push({ piece: piece, layer: layer });
                    }
                });
            });

            this.$store.commit('designer/SET_EXCEED_STITCHES', result)
        },

        // 刺绣超出针数限制
        getEmbPlatenColors () {
            const result = [];
            // this.pieces.map((piece) => {
            //     piece.layers.map((layer) => {
            //         if (piece.type == 2) {
            //             const color = layer.dists.reduce((pre, cur) => pre + cur.line_color.split(',').length, 0)
            //             color > 90 && result.push({ piece: piece, layer: layer });
            //         }
            //     });
            // });

            // this.$store.commit('designer/SET_EXCEED_COLORS', result)
        },

        // 修改选中状态
        setNotifyActive (item) {
            item.piece && this.$store.commit("designer/SET_ACTIVE_PIECE", item.piece);
            if (item.layer) {
                this.$store.commit("designer/SET_ACTIVE_LAYER_INDEX", item.piece.layers.indexOf(item.layer));
                if (item.dst) {
                    this.$store.commit("designer/SET_ACTIVE_DST_INDEX", item.layer.dists.indexOf(item.dst));
                } else {
                    this.$store.commit("designer/SET_ACTIVE_DST_INDEX", -1);
                }

                setTimeout(() => this.$emit('global:DESIGN_SCROLL_TO_LAYER'), 10);
            }

        }
    },

    created () {
        this.$on("global:DESIGN_NOTIFY_CHECK", () => {
            setTimeout(() => {
                this.getEmbDstOverlap()
                this.getEmbDstOversize();
            }, 0);
        });
        this.$on("global:DESIGN_NOTIFY_LIMIT", () => {
            setTimeout(() => {
                this.getEmbPlatenExcess()
                this.getEmbPlatenColors()
            }, 0)

        });

    }
};
</script>
<style lang="scss" scoped>
.notify-clarity,
.notify-oversize,
.notify-overlap {
    position: absolute;
    bottom: 20px;
    left: 24px;
    right: 24px;
    padding: 12px;
    font-family: Roboto, Roboto;
    font-weight: 400;
    font-size: 16px;
    color: #c62828;
    background: #fef6f6;
    border-radius: 12px;
    border: 1px solid #f7eeee;
    z-index: 5;
    text-align: center;
    line-height: 24px;

    svg {
        width: 14px;
        height: 14px;
        position: relative;
        top: -2px;
        vertical-align: middle;
    }

    span {
        text-decoration: underline;
        cursor: pointer;

        &:hover {
            color: #aa1f1f;
            text-decoration: none
        }
    }
}
</style>
